<?php

namespace App\Http\Controllers\Api\Auth;

use App\Http\Controllers\Api\ApiController;
use App\Models\Admin;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Str;

class AuthController extends ApiController
{
    /**
     * 管理员登录
     */
    public function login(Request $request)
    {
        $request->validate([
            'username' => 'required|string',
            'password' => 'required|string',
        ]);

        // 限流检查
        $throttleKey = Str::lower($request->username).'|'.$request->ip();

        if (RateLimiter::tooManyAttempts($throttleKey, 10)) {
            $seconds = RateLimiter::availableIn($throttleKey);
            return $this->error("登录失败次数过多，请 {$seconds} 秒后再试", 429);
        }

        // 查找管理员
        $admin = Admin::where('username', $request->username)
            ->orWhere('email', $request->username)
            ->first();

        // 验证凭据
        if (!$admin || !Hash::check($request->password, $admin->password)) {
            RateLimiter::hit($throttleKey);
 // 记录登录失败日志
            $this->logLoginAttempt($request->username, $request->ip(), false);

            return $this->error('用户名或密码错误', 401);
        }

        // 检查账户状态
        if ($admin->status !== 1) {
            return $this->error('账户已被禁用', 401);
        }

        // 清除限流记录
        RateLimiter::clear($throttleKey);

        // 记录登录成功日志
        $this->logLoginAttempt($request->username, $request->ip(), true, $admin->id);

        // 更新最后登录时间
        $admin->update([
            'last_login_at' => now(),
            'last_login_ip' => $request->ip(),
        ]);

        // 创建token（使用 Sanctum）
        $token = $admin->createToken('admin-token')->plainTextToken;

        return $this->success([
            'admin' => $admin,
            'token' => $token,
            'token_type' => 'Bearer'
        ], '登录成功');
    }

    /**
     * 管理员登出
     */
    public function logout(Request $request)
    {
        $request->user()->currentAccessToken()->delete();

        return $this->success(null, '登出成功');
    }

    /**
     * 获取当前用户信息
     */
    public function me(Request $request)
    {
        $admin = $request->user();
        $admin->load('roles.permissions');

        return $this->success($admin);
    }

    /**
     * 记录登录尝试日志
     */
    private function logLoginAttempt($username, $ip, $success, $adminId = null)
    {
        // TODO: 实现登录日志记录
        // 这里可以记录到 admin_login_logs 表中
    }
}
